#! /usr/bin/python
# coding=utf-8

import os
import threading
import time
import redis
import json
import sys
import signal
import urllib
import urllib2

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from tdm_config.tdm_config import *

reload(sys)
sys.setdefaultencoding('utf-8')

DEBUG = True

server_sleep = 300
server_delay = 0.1

posturl = "http://175.25.244.139:8102/recv/network"
#posturl = "http://127.0.0.1:8102/recv/network"

def read_ip_addr_from_file(f_name):
    net_dev_list = []
    f = open(f_name)
    try:
        for line in f:
            dev_list = line.strip('\r\n').split('\t')
            if len(dev_list) == 3:
                if '' in dev_list:
                    continue
                else:
                    net_dev = {}
                    net_dev['jxd'] = dev_list[0]
                    net_dev['device'] = dev_list[1]
                    net_dev['ip'] = dev_list[2]
                    net_dev_list.append(net_dev)
    finally:
        f.close()

    return net_dev_list

def read_ip_addr_from_redis():
    r = redis.Redis(host='127.0.0.1', db=1)
    net_dev_list = []
    for city_jxd_dev, ipaddr in r.hgetall(tdm_redis_key_network).items():
        city, jxd, dev = city_jxd_dev.split('_')
        net_dev = {}
        net_dev['city'] = city
        net_dev['jxd'] = jxd
        net_dev['device'] = dev
        net_dev['ip'] = ipaddr
        '''
        if not (city == '北京' and jxd == '综合楼' and dev == '路由'):    #北京_综合楼_路由
            continue
        '''
        net_dev_list.append(net_dev)
    return net_dev_list

def post(url, data):
    data = urllib.urlencode(data)
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req, timeout=5)
    return response.read()


class multi_network_ping(threading.Thread):
    def __init__(self, city, jxd, device, ip):
        threading.Thread.__init__(self)
        self.city = city
        self.jxd = jxd
        self.device = device
        self.ip = ip
        self.thread_stop = False
 
    def run(self):
        ret_network_ping = {}

        #while not self.thread_stop:
        cmd = 'ping -c 3 -n -w 3 %s > /dev/null 2>&1' % (self.ip,)
        ret = os.system(cmd)
        key = '%s_%s_%s_%s' % (self.city, self.jxd, self.device, tdm_redis_key_network_online_suffix)
        if ret == 0:
            ret_network_ping[key] = 1
        else:
            ret_network_ping[key] = 0

        if DEBUG:
            print key, ret_network_ping[key]

        ret = post(posturl, ret_network_ping)

    def stop(self):
        self.thread_stop = True

def network_ping_start():
    #dev_list = read_ip_addr_from_file('ics3.0_ip_addr.txt')
    dev_list = read_ip_addr_from_redis()

    multi_thread_list = []

    for dev in dev_list:
        multi_thread_list.append(multi_network_ping(dev.get('city'), dev.get('jxd'), dev.get('device'), dev.get('ip')))

    for serv_thread in multi_thread_list:
        serv_thread.setDaemon(True)
        serv_thread.start()
        time.sleep(server_delay)

    for serv_thread in multi_thread_list:
        serv_thread.join()


if __name__ == '__main__':
    while True:
        network_ping_start()
        time.sleep(server_sleep)
